//
// Created by postgres on 4/20/17.
//
#include "../include/04String/myString.h"
Status StrAssign(SeqString *s,char chr[]){
    int i;
    char a;

    for(i=0;chr[i]!='\0';i++){
        if(i>=MaxLength-1)break;
        s->str[i]=chr[i];
    }
    s->length=i;
    s->str[i]='\0';
    return  OK;
}
int str_len(SeqString s){
    return s.length;
}
Status StrEmpty(SeqString S)
/*判断串是否为空，串为空返回1，否则返回0*/
{
    if(S.length==0)         /*判断串的长度是否等于0*/
        return 1;           /*当串为空时，返回1；否则返回0*/
    else
        return 0;
}

/**
 *
 * @param s source string
 * @param index: from 0 to n,a0.....an
 * @param sub substring
 * @return 1 representation full insert,0 representation section insert
 * cut source string,cut substring
 */
Status StrInsert(SeqString *s,int index,SeqString sub){
    int i;
    if(index<0||index+1>s->length){
        printf("index overstep the boundary");
    }
    Size sub_len=sub.length;
    Size Len=s->length;
    if(s->length+sub.length<=MaxLength){
        for(i=0;i<Len-index;i++){
            s->str[Len+sub_len-i-1]=s->str[Len-i-1];
        }
        for(i=0;i<sub_len;i++){
            s->str[index+i]=sub.str[i];
        }
        s->str[sub_len+Len]='\0';
        return  OK;
    } else if(index+sub.length<=MaxLength){
        //cut source string of rear,keep sub
        size_t sum=MaxLength-sub_len-index;
        for(i=0;i<sum;i++){
           s->str[MaxLength-1-i]=s->str[MaxLength-sub_len-1-i];
        }
        for(i=0;i<sub_len;i++){
            s->str[index+i]=sub.str[i];
        }
        //s->str[MaxLength-1]='\0';
        return ERROR;

    }else if(index+sub.length>MaxLength){
        //cut source substring and may cut source string
        for(i=0;i<sub_len;i++){
            s->str[index+i]=sub.str[i];
        }
        s->str[MaxLength-1]='\0';
        return ERROR;
    }
}
Status StrDelete(SeqString *s,int index,int len){
    if(len<1||len>s->length||index<0||index>=s->length)return  ERROR;
    int i,sum;
    sum=s->length-index-len;
    for(i=0;i<sum;i++){
        s->str[index+i]=s->str[index+len+i];
    }
    s->length=s->length-len;
    s->str[s->length]='\0';
}
Status subString(SeqString *sub,int index,int len,SeqString s){
    if(len<1||len>s.length||index<0||index>=s.length||index+len>s.length)return  ERROR;
    int i;
    for(i=0;i<len;i++){
        sub->str[i]=s.str[index+i];
    }
    sub->length=i;
    return OK;
}
void string_test(){
    //char chr[]="0123456789";
    SeqString s,sub;
    StrAssign(&s,"0123456789");
    StrAssign(&sub,"abc");
    //StrInsert(&s,3,sub);
    //StrDelete(&s,3,3);
    subString(&sub,3,3,s);
}
